package com.wenc.psi.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**JDBC工具类**/
public class JDBCUtils {

    protected static Connection conn;
    protected static Statement stmt;
    protected static PreparedStatement pstmt;
    protected static ResultSet rs;

    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    /**
     * 文件的读取，读取一次，静态代码块
     */
    static {
        //读取资源文件，获取值。
        try {
            //1.创建Properties集合类
            Properties pro = new Properties();
            //2.加载文件
            pro.load(JDBCUtils.class.getResourceAsStream("/assets/jdbc.properties"));
            //3.获取数据，赋值
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            System.out.println(url+user+password);
            //4.注册驱动
            System.out.println("加载驱动");
            Class.forName(driver);
            System.out.println("驱动加载成功");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * return连接对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }

    /**
     * 释放资源
     * stmt
     * conn
     */
    public static void close(Statement stmt, Connection conn) {
        close(null, stmt, conn);
    }

    /**
     * 释放资源
     * rs
     * stmt
     * conn
     */
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs !=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (stmt !=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (conn !=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

